//
//  RecommendationViewController.m
//  NBTripe
//
//  Created by Lee on 16/1/7.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "RecommendationViewController.h"
#import "RecommendSecondModel.h"
#import "GoodStoryViewController.h"
#import "TitleTableViewCell.h"
#import "GoodStoysCollectionViewCell.h"
#import "LTWebViewTableViewCell.h"
#import "CustomTableViewCell.h"
#import "GoodStorysDetailViewController.h"
#import "RecommendCustomViewController.h"

@interface RecommendationViewController ()<UITableViewDataSource, UITableViewDelegate, WebDetegate, UICollectionViewDataSource, UICollectionViewDelegate, ChangeNextPage, UIScrollViewDelegate>
//大数组
@property (nonatomic, strong) NSArray *elementsarray;
//轮播图数组
@property (nonatomic, strong) NSMutableArray *focusimagearr;
//每日精选故事数组
@property (nonatomic, strong) NSMutableArray *gooddaystoryarr;
//标题数组
@property (nonatomic, strong) NSMutableArray *titlearray;
//webcell数组
@property (nonatomic, strong) NSMutableArray *webarr;
//自定义cell数组
@property (nonatomic, strong) NSMutableArray *customarr;
//Uitableview
@property (nonatomic, strong) UITableView *tableview;
//精彩故事上的collectionview
@property (nonatomic, strong) UICollectionView *collectionview;
//加载动画
@property (nonatomic, strong) MBProgressHUD *load;
//y偏移量
@property (nonatomic, assign) CGFloat content_y;
//加载动画
@property (nonatomic, strong) UIImageView *LoadAnimation;
//刷新拼接页数
@property (nonatomic, strong) NSNumber *page;

@end

@implementation RecommendationViewController


- (void)viewDidLoad {
   
    self.focusimagearr = [[NSMutableArray alloc] initWithCapacity:0];
    self.gooddaystoryarr = [[NSMutableArray alloc] initWithCapacity:0];
    self.titlearray = [[NSMutableArray alloc] initWithCapacity:0];
    self.webarr = [[NSMutableArray alloc] initWithCapacity:0];
    self.customarr = [[NSMutableArray alloc] initWithCapacity:0];
    [self getDataSource];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(shoucangAlert:) name:@"alertView" object:nil];
    
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor colorWithRed:0.29 green:0.74 blue:0.8 alpha:1];
     self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.29 green:0.74 blue:0.8 alpha:1];
}
/**
 *  收藏alert
 */
- (void)shoucangAlert:(NSNotification *)sender {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"真的要删除此收藏吗" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIButton *button = [sender.userInfo objectForKey:@"button"];
        button.tintColor = [UIColor whiteColor];
        NSArray *arr = [sender.userInfo objectForKey:@"storage"];
        
        [[CoreDataManager shareManager].managedObjectContext deleteObject:[arr lastObject]];
        [[CoreDataManager shareManager]saveContext];
    }]];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}
/**
 *  创建tableview
 */
- (void)createTableview {
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HIGHT- 108) style:UITableViewStylePlain];
    self.tableview.dataSource = self;
    self.tableview.delegate = self;
    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
    //标题cell
    [self.tableview registerClass:[TitleTableViewCell class] forCellReuseIdentifier:@"TitleTableViewCell"];
    //webcell
    [self.tableview registerClass:[LTWebViewTableViewCell class] forCellReuseIdentifier:@"LTWebViewTableViewCell"];
    //自定义大图cell
    [self.tableview registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"CustomTableViewCell"];
    self.tableview.backgroundColor = [UIColor whiteColor];
    self.tableview.separatorStyle =  UITableViewCellSeparatorStyleNone;
    //防止循环引用
    __weak RecommendationViewController *weakself = self;
    //下拉加载
    [self.tableview addFooterWithCallback:^{
        [weakself addFooter];
    }];
    //上拉刷新
    [self.tableview addHeaderWithCallback:^{
        [weakself getDataSource];
 
    }];
    [self.view addSubview:self.tableview];
}
/**
 *  获取网络数据
 */
- (void)getDataSource {
   
    //判断网络状态
    if ([ReachabilityManager sharedReachabilityManager].currentReachabilityStatus == NotReachable) {
        [KVNProgress showErrorWithStatus:@"请检查网络"];
        return;
    }
    
    if ([ReachabilityManager sharedReachabilityManager].currentReachabilityStatus == ReachableViaWWAN) {
        [KVNProgress showErrorWithStatus:@"您正处于非WIFI状态下"];
    }
    [KVNProgress show];
    [XYNetWorkTool getWithUrl:kRecommendtionURL parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        if (self.webarr.count > 0) {
            [self.webarr removeAllObjects];
            [self.customarr removeAllObjects];
            [self. gooddaystoryarr removeAllObjects];
        }
       
        NSDictionary *dic = result;
        self.page = [[dic objectForKey:@"data"] objectForKey:@"next_start"];
       
        //获取推荐主界面的大数组
        NSArray *elementsarr = [[dic objectForKey:@"data"] objectForKey:@"elements"];
        self.elementsarray = [NSArray arrayWithArray:elementsarr];
       //轮播图数组获取数据
        self.focusimagearr = [[[elementsarr firstObject] objectForKey:@"data"] firstObject];
      
        for (NSDictionary *dic in elementsarr) {
        
            NSInteger type = [[dic objectForKey:@"type"] intValue];
            if(type != 1) {
            NSDictionary *seconddic = [[dic objectForKey:@"data"] firstObject];
            RecommendSecondModel *model = [[RecommendSecondModel alloc] initWithDataSource:seconddic];
          //  NSLog(@"++++++%@", model);
             ;
            //每日精选故事数组获取数据
            if (type == 10) {
                [self.gooddaystoryarr addObject:model];
            }
            //标题数组获取数据
            else if (type == 11 || type == 9) {
                [self.titlearray addObject:model];
               // NSLog(@"%@", model.title);
            }
        //web cell数组获取数据
            else if (type == 7) {
                [self.webarr addObject:model];
            }
        //custom cell数组获取数据
            else if (type == 4) {
                [self.customarr addObject:model];
            }
         
        }
        }
        
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            //NSLog(@"++++++%ld", _customarr.count);
            [self createTableview];
            [self loadAnimation];
            [self addfocusimageheaderview];
        });
       
        [KVNProgress dismiss];
    } fail:nil];
}
/**
 *  轮播图
 */
- (void)addfocusimageheaderview {
    NSMutableArray *focusimagearray = [[NSMutableArray alloc] initWithCapacity:0];
    NSMutableArray *focusurlarray = [[NSMutableArray alloc] initWithCapacity:0];
 
    for (NSDictionary *dic in self.focusimagearr) {
        [focusimagearray addObject:[dic objectForKey:@"image_url"]];
        [focusurlarray addObject:[dic objectForKey:@"html_url"]];
    }
    ScrollWithImage *focusimageviews = [[ScrollWithImage alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 220) withArray:focusimagearray witnArrayurl:focusurlarray withArrayId:nil];
    focusimageviews.tag = 1001;
    focusimageviews.detegate = self;
     self.tableview.tableHeaderView = focusimageviews;
}
/**
 *  轮播图点进去
 */
- (void)getWeb:(NSString *)myurl {
    WebViewController *webVC = [[WebViewController alloc] init];
    webVC.url = myurl;
    [self.navigationController pushViewController:webVC animated:YES];
}
/**
 *  tableview协议方法
 */

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _webarr.count+_customarr.count+3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 || indexPath.row == 2) {
        return 30*XHIGHT;
    }
    else if(indexPath.row == 1)
        return 430*XHIGHT;
    else
        return 210*XHIGHT;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    if (indexPath.row == 0) {
        TitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TitleTableViewCell"];
        cell.titletitle = [self.titlearray[0] title];
        cell.pagedelegate = self;
        [cell qianjinbutton];
        return cell;
    }
    else if (indexPath.row == 1) {
        // self.tableview.userInteractionEnabled = NO;
        [self addCollectionview];
        [cell addSubview:self.collectionview];
    }
    else if (indexPath.row == 2) {
        TitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TitleTableViewCell"];
        cell.titletitle = [self.titlearray[1] title];
        return cell;
    }
    else {
     
        if (indexPath.row > 2 && indexPath.row <= _webarr.count+2 ) {
            LTWebViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LTWebViewTableViewCell"];
            cell.model = self.webarr[indexPath.row-3];
            
            return cell;
        }
       else {
            CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomTableViewCell"];
           NSInteger row = indexPath.row - self.webarr.count-3;
           cell.model = self.customarr[row];
           cell.usermodel = [self.customarr[row] usermodel];
            return cell;
        }
    }
 
    return cell;
}
/**
 *  tableview点击事件
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row > 2 && indexPath.row <= _webarr.count+2 ) {
      // 点击进入web
        WebViewController *webVC = [[WebViewController alloc] init];
        NSString *urls = [self.webarr[indexPath.row-3] urls];
        [webVC WebUrl:urls];
        [self.navigationController pushViewController:webVC animated:YES];
    }
    else if(indexPath.row > _webarr.count && indexPath.row <=_customarr.count+_webarr.count+2) {
        RecommendCustomViewController *customVC = [[RecommendCustomViewController alloc] init];
        customVC.joinedId = [[self.customarr[indexPath.row-3-_webarr.count] joinedId] stringValue];
        [self.navigationController pushViewController:customVC animated:YES];
    }
}

/**
 *  创建精彩故事的collection
 */
- (void)addCollectionview {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.itemSize = CGSizeMake(WIDTH/2-5, 200*XHIGHT);
    flowLayout.minimumLineSpacing = 10*XHIGHT;
    self.collectionview = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 430*XHIGHT) collectionViewLayout:flowLayout];
    //scrollview关闭适配
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.collectionview.dataSource = self;
    self.collectionview.delegate = self;
    self.collectionview.bounces = NO;
    self.collectionview.userInteractionEnabled = YES;
    self.collectionview.backgroundColor = [UIColor whiteColor];
    [self.collectionview registerNib:[UINib nibWithNibName:@"GoodStoysCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"GoodStoysCollectionViewCellIdentifier"];
    self.collectionview.pagingEnabled = YES;
}
/**
 *  CollectionView的协议方法
 */
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 4;
}
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    GoodStoysCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GoodStoysCollectionViewCellIdentifier" forIndexPath:indexPath];
    //精彩故事传值
    
       cell.model = self.gooddaystoryarr[indexPath.row];
    cell.usermodel = [self.gooddaystoryarr[indexPath.row] usermodel];

    return cell;
}
/**
 *  collectionview点击事件
 */
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GoodStorysDetailViewController *detailVC = [[GoodStorysDetailViewController alloc] init];
   // NSLog(@"%@", [self.gooddaystoryarr[indexPath.row] spotId]);
    detailVC.spotId = [self.gooddaystoryarr[indexPath.row] spot_id];
    
    detailVC.usermodel = [self.gooddaystoryarr[indexPath.row] usermodel];
    [self.navigationController pushViewController:detailVC animated:NO];
}

/**
 *  点击全部进入精彩故事页面
 */
- (void)nextpage {
    GoodStoryViewController *storyVC = [[GoodStoryViewController alloc] init];
    [self.navigationController pushViewController:storyVC animated:YES];
}

//加载动画
- (void)loadAnimation {
    self.LoadAnimation = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    self.LoadAnimation.image = [UIImage sd_animatedGIFNamed: @"jiazai"];
    [self.view addSubview:self.LoadAnimation];
}
//将要开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.content_y = scrollView.contentOffset.y;
    // NSLog(@"%f", _content_y);
}
//偏移触发
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < 0) {
        //NSLog(@"上拉");
        self.LoadAnimation.frame = CGRectMake(0, 0, WIDTH, -scrollView.contentOffset.y);
        }
    
}
//结束拖拽触发
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    self.LoadAnimation.frame = CGRectMake(0, 0, 0, 0);
    [self.tableview headerEndRefreshing];

}
- (void)addFooter {
    NSString *newpage = self.page.stringValue;
   // NSLog(@"++++++++%@", newpage);
    [XYNetWorkTool getWithUrl:kRecommendtionRefresh(newpage) parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id reslut) {
        NSDictionary *dic = reslut;
        NSArray *elementarr = [[dic objectForKey:@"data"] objectForKey:@"elements"];
        for (NSDictionary *dic in elementarr) {
        NSDictionary *seconddic = [[dic objectForKey:@"data"] firstObject];
        NSInteger type = [[dic objectForKey:@"type"] intValue];
            if (type == 4) {
                RecommendSecondModel *model = [[RecommendSecondModel alloc] initWithDataSource:seconddic];
                [self.customarr addObject:model];

            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableview reloadData];
           // 刷新完成后结束footer的刷新状态
            [self.tableview footerEndRefreshing];
            
        });
    } fail:nil];
}

@end
